#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/10/26 14:19
# @Author  : HYCX-AI-LAB Liang jinhao

"""
自定义线程 抓取线程内的报错
"""

import threading
import traceback
import sys


class EpaiThread(threading.Thread):
    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, daemon=None):
        super(EpaiThread, self).__init__(group=group, target=target, name=name, args=args, kwargs=kwargs, daemon=daemon)
        self.exitcode = 0
        self.exception = None
        self.exc_traceback = ''

    def run(self):
        try:
            if self._target:
                self._target(*self._args, **self._kwargs)
        except Exception as e:
            self.exception = e
            self.exitcode = 1  # 如果线程异常退出，将该标志位设置为1，正常退出为0
            self.exc_traceback = ''.join(traceback.format_exception(*sys.exc_info()))  # 在改成员变量中记录异常信息
        finally:
            del self._target, self._args, self._kwargs


def start_thread(target):
    thread_service = EpaiThread(target=target)
    thread_service.setDaemon(True)
    thread_service.start()
    thread_service.join()
    return thread_service


def raise_from_thread(epai_thread):
    if epai_thread.exitcode == 1:
        raise epai_thread.exception
